<?php
/**
 * Created by .
 * User: luogan
 * Date: 2022/1/17
 */

namespace app\admin\service;


use lib\Excel;

class BaseService
{
    use Excel;

    /**
     * 配合withSearch搜索器使用
     * @param $data
     * @param bool $_area 是否显示地区权限数据
     * @return array
     */
    protected function searchFields($data){
        unset($data['page']);
        unset($data['size']);
        $data = array_keys($data);
        return $data;
    }

    /**
     * 配合withSearch搜索器使用
     * @param $data
     * @param bool $_area
     * @return mixed
     */
    protected function searchData($data){
        unset($data['page']);
        unset($data['size']);
        return $data;
    }

    /**
     * 获取分页条数
     * @param $data
     * @return int
     */
    protected function getLimit($data){

        $size = 15;
        if (isset($data['size'])){
            $size = $data['size'];
        }
        return $size;
    }


    /**
     * @Title: Excel表格导出
     * @Date: 2021/11/9
     * @Interface tableExport
     * @param $data
     * @param $filed
     * @param $total
     * @param $template
     * @param string $filename
     * @return array
     */
    protected function tableExport($data, $filed, $total, $template, $filename = '导出数据')
    {

        $template = request()->get('xls', $template);
        $save_path = Excel::export($data, $filed, $template, $filename . '-' . date('YmdHis'));
        //计算进度
        $limit = 10;
        $page = 1;
        $rate = $page * $limit / $total * 100;
        $percent = $rate > 100 ? 100 : $rate;
        $data = [
            'download' => $percent >= 100 ? request()->domain() . '/' . $save_path : '',
            'path' => $save_path,
            'percent' => $percent
        ];
        return $this->tableJson($data, $total);
    }


    /**
     * @Title:Excel表格导入
     * @Date: 2021/11/9
     * @Interface tableImport
     * @param $filepath
     * @param $filedList
     * @return array
     */
    protected function tableImport($filepath, $filedList)
    {
        $data = Excel::import($filepath, $filedList);
        return $data;
    }

    /**
     * 返回表格数据
     * @param $data
     * @param $total
     * @return array
     */
    protected function tableJson($data, $total)
    {
        $json = [
            'data' => $data,
        ];
        if ($total) {
            $json = array_merge($data, ['count' => $total]);
        }
        return $json;
    }
}
